import * as React from 'react';
import ViewportStore from '../store/viewport';
import Helper from './helper/helper.component';
import { Props, State } from './render.type';
import * as _ from 'lodash';

export class GaeaRender extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  private viewport = new ViewportStore();

  public componentDidMount() {
    this.handleFormValueChange();
  }

  public componentDidUpdate(prevProps: Props) {
    if (!_.isEqual(prevProps.formValues, this.props.formValues)) {
      this.handleFormValueChange();
    }
  }

  public UNSAFE_componentWillMount() {
    // 设置基础组件
    this.props.componentClasses?.forEach((componentClass) => {
      this.viewport.addComponentClass(componentClass);
    });

    // 设置页面
    if (this.props.value) {
      Object.keys(this.props.value).forEach((instanceKey) => {
        const instanceInfo = this.props.value[instanceKey];
        this.viewport.instances.set(instanceKey, instanceInfo);

        // 设置根 mapUniqueKey
        if (instanceInfo?.parentInstanceKey === null) {
          this.viewport.setRootUniqueId(instanceKey);
        }
      });
    }

    this.viewport.event.on(this.viewport.event.onCall, this.handleOnCall);
  }

  public UNSAFE_componentWillUnmount() {
    this.viewport.event.off(this.viewport.event.onCall, this.handleOnCall);
  }

  public handleFormValueChange() {
    if (this.props.form && this.props.formValues) {
      try {
        // warning.js:34 Warning: You cannot set a form field before rendering a field associated with the value.
        // todo ?? 这样写，不会报上面的警告？？？
        const keys = Object.keys(this.props.formValues) || [];
        const initValues = this.props.form.getFieldsValue(keys);
        console.log('initValues----{}', initValues);
      } catch (e) {
        console.log(e);
      }
      setTimeout(() => {
        this.props.form?.setFieldsValue(this.props.formValues);
      });
    }
    // 设置外部传参
    this.viewport.setParams({
      formValues: this.props.formValues
    });
    // 调用 forceUpdate() 将致使组件调用 render() 方法，此操作会跳过该组件的 shouldComponentUpdate()。
    this.forceUpdate();
  }
  
  /**
   * 触发调用事件
   */
  public handleOnCall = (_context: any, eventData: any) => {
    if (this.props.onCall) {
      this.props.onCall(eventData.functionName, eventData.param);
    }
  };

  public render() {
    if (!this.viewport.rootInstanceKey) {
      return null;
    }

    return (
      <Helper
        layout={this.props.layout}
        rows={this.props.rows}
        renderMode={this.props.renderMode}
        viewport={this.viewport}
        disabled={this.props.disabled}
        instanceKey={this.viewport.rootInstanceKey}
        form={this.props.form}
      />
    );
  }
}
